import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {SearchForm,Approval} from '../../components/party-appraisal'
import { FormattedMessage  } from 'react-intl';
import { stripesConnect, IfPermission } from '@folio/stripes/core';
import get from 'lodash/get';
import {
  MultiColumnList,
 
  Checkbox
} from '@folio/stripes/components';
import {
  StripesConnectedSource
} from '@folio/stripes/smart-components';
import ExprotExcel from '../../util/ExportExcel';
class list extends Component {
  static manifest = Object.freeze({
    appraisalQuery: { initialValue: ' (partyId = *) ' },
    resultCount: { initialValue: 10 },
    AppraisalRecords: {
      type: 'okapi',
      path: 'party/appraisal',
      recordsRequired: '%{resultCount}',
      perRequest: 10,
      limitParam: 'limit',
      records: 'appraisalGroup',
      GET: {
        params: {
          query: ' %{appraisalQuery}  sortby createDate/sort.descending '
        }
      }
    }
    ,AppraisalRecordsExportExcel:{
      type:'okapi',
      path: 'party/appraisal/export_excel',
      accumulate: true,
      fetch: false
    },AppraisalDelRecords:{
      type:'okapi',
      path: 'party/appraisal/batchDel',
      accumulate: true,
      fetch: false
    }
  })
  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
     partyQuery: PropTypes.string,
      AppraisalRecords: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      }) ,
      AppraisalRecordsExportExcel:PropTypes.shape({
       GET: PropTypes.func.isRequired,
       }) ,
       AppraisalDelRecords:PropTypes.shape({
         POST: PropTypes.func.isRequired,
      })
    }).isRequired,
   okapi:PropTypes.object,
    toModel:PropTypes.func,
    intl:PropTypes.object
  };
  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state={
      query:' (partyId = *) sortby createDate/sort.descending  ',
      queryJSONStr:'',
      operator:{},
      isAllChecked: false,
      checkedState: {},
      selected: [],
      isOpen:false
    }
  }
  search=({...form})=>{
    const {query,queryJSONStr} = this.state
    const queryObjectStr = JSON.stringify(form);
    const {mutator}=this.props
    if(queryJSONStr === queryObjectStr){
      return false;
    }
   
    let queryList = []
    const params = form
    if(!!params.partyName){
      queryList.push(` partyName == *${params.partyName}* `)
    }
    if(!!params.readerName){
      queryList.push(` readerReserveGroup == *"name"*: *"${params.readerName}"* `)
    }
    if(!!params.readerAccount){
      queryList.push(` readerReserveGroup == *"barcode"*: *"${params.readerAccount}"* `)
    }
    if(!!params.state){
      queryList.push(` state = ${params.state} `)
    }
    if(!!params.partyStartDate){
      queryList.push(` createDate >= ${params.partyStartDate} 00:00:00 `)
    
    }
    if(!!params.partyEndDate){
      queryList.push(` createDate <= ${params.partyEndDate} 23:59:59 `)
    }
    if(!!params.score){
      queryList.push(` score = ${params.score} `)
    }
  
   let queryParams=queryList.join(' and ')
   if(!queryParams){
     queryParams = '(partyId == *)'
   }else{
     queryParams = `(${queryParams})`
   }
    if(this.source){
      mutator.appraisalQuery.replace(queryParams);
      this.setState({
        queryJSONStr:queryObjectStr,
        query:queryParams
      })
    }
   
  }
  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
    const { currentUser } = this.props.okapi;
    if (currentUser) {
      this.setState({
        operator: currentUser
      });
    }
  }

  componentDidUpdate() {
    this.source.update(this.props,'AppraisalRecords');
  }

  componentWillUnmount() {
    const {
      mutator
    } = this.props;
    mutator.appraisalQuery.replace('');
  }

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  }
  checkChange=(e)=>{
    const input = e.currentTarget;
    this.setState(prevState => {
      const selectedArray = prevState.selected;
      const checkedState = prevState.checkedState;
      if (input.checked) {
        selectedArray.push(input.value);
        checkedState[input.value] = true;
      } else {
        selectedArray.splice(selectedArray.indexOf(input.value), 1);
        checkedState[input.value] = false;
      }
      return {
        isAllChecked: false,
        selected: selectedArray,
        checkedState
      };
    });
  }
  allCheckToggle=()=>{
    const {
      resources
    } = this.props;
    this.setState((prevState) => {
      const dataList = get(resources, 'AppraisalRecords.records', []);
      const selectedArray = [];
      const checkedState = prevState.checkedState;
      if (!prevState.isAllChecked) {
        dataList.forEach((value, index) => {
          selectedArray.push(value.id);
          checkedState[value.id] = true;
        });
        return { selected:selectedArray, isAllChecked:true, checkedState };
      } else {
        dataList.forEach((value, index) => {
          checkedState[value.id] = false;
        });
        return { selected:selectedArray, isAllChecked:false, checkedState };
      }
    });
  }
  commitApproval=({...form})=>{
     if(form.state == 2 && !form.remark){
        alert("请在备注填写你拒绝这些评论的理由")
        return;
     }
     form.idList = this.state.selected;
     const okapi = this.props.okapi;
     const currentUser = okapi.currentUser
     form.checker = currentUser.username;
     const {
      mutator
    } = this.props;
     mutator.AppraisalRecords.POST(form).then((response)=>{
      this.setState({isOpen:false})
      this.source.update(this.props,'AppraisalRecords');
     })
    
  }
  exportData=()=>{
    const params = {
      limit:10,
      query:this.state.query
    };
    
    const p = params;
    const okapi = this.props.okapi;
    const path = okapi.url + '/party/appraisal/export_excel';
    const requestParams = ExprotExcel.objToParam(p);
    const fileName = '读者评论';
    const type = 'GET';
    
    ExprotExcel.exprot(
      path,
      requestParams,
      type,
      fileName,
      okapi.token,
      okapi.tenant
    );
     
  }
  batchDeleteData=()=>{
    const selectedList=this.state.selected;
    const {POST}=this.props.mutator.AppraisalDelRecords;
    if(selectedList.length === 0){
      alert('请至少选择一条记录!')
      return false;
    } 
    let request = {
      idList:selectedList
    }
    POST(request).then(res=>{
      this.source.update(this.props,'AppraisalRecords');
    })
  }
  render() {
    const {
      resources,
    } = this.props;
    if (this.source) {
      this.source.update(this.props,'AppraisalRecords');
    }
    const totalCount = this.source ? this.source.totalCount() : 0;
    const dataList = get(resources, 'AppraisalRecords.records', []);
    const resultsFormatter={
      checkBox: item => {
        return (
          <Checkbox name="selectList" checked={this.state.checkedState[item.id]} onClick={this.checkChange} value={item.id} />
        );
      },partyName:item =>{
      return  <div
       title={item.partyName}
       style={{
         whiteSpace: 'nowrap',
         overflow: 'hidden',
         textOverflow: 'ellipsis'
       }}
     >
       {item.partyName}
     </div>
      },
      readName: item =>{
      return <div>{item.readerReserveGroup[0].name}</div>
      },
      readerAccount:item =>{
        return <div>{item.readerReserveGroup[0].barcode}</div>
        },
      state: item =>{
        if (item.state === '0') {
          return <div><FormattedMessage id={"ui-party.loans.columns.unreviewed"}/></div>;
        } else if (item.state === '1') {
          return <div><FormattedMessage id={"ui-party.loans.columns.reviewed"}/></div>;
        }  else if (item.state === '2') {
          return <div><FormattedMessage id={"ui-party.other.unapproved"}/></div>;
        } 
      },
      appraisal:item =>{
        return  <div
        title={item.appraisal}
        style={{
          whiteSpace: 'nowrap',
          overflow: 'hidden',
          textOverflow: 'ellipsis'
        }}
      >
        {item.appraisal}
      </div>
      },
      serialNumber: item => [<span>{item.rowIndex + 1}</span>],
      score:item => [<span>{item.score}星</span>]
    }
    return (
      <div>
        <Approval isOpen={this.state.isOpen} closeModal={()=>{
          this.setState({isOpen:false})
        }} onSubmit={this.commitApproval} initialValues={{state:"1"}} />
        <SearchForm onSubmit={this.search} exportData={this.exportData} batchDeleteData={this.batchDeleteData} openApproval={()=>{
            const selectedList=this.state.selected;
            if(selectedList.length === 0){
              alert('请至少选择一条记录!')
              return false;
            }else{
              this.setState({isOpen:true})
            }
        }}/>
        <MultiColumnList
          height={500}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          interactive={false}
          totalCount={totalCount}
          virtualize
          contentData={dataList}
          onNeedMoreData={this.moreData}
          formatter={resultsFormatter}
          visibleColumns={['checkBox', 'serialNumber','appraisal', 'score','readerAccount', 'readName', 'createDate', 'state','checker'   ]}
          columnMapping={{
            checkBox: <Checkbox checked={this.state.isAllChecked} onChange={this.allCheckToggle} />,
            serialNumber: (
              <FormattedMessage id="ui-party.loans.columns.serialNumber" />
            ),
            readerAccount: <FormattedMessage id="ui-party.loans.columns.party.appraisal.account" />,
            readName: <FormattedMessage id="ui-party.loans.columns.party.appraisal.name" />,
            state: <FormattedMessage id="ui-party.loans.columns.party.approvalStatus" />,
            appraisal:<FormattedMessage id="ui-party.loans.columns.party.appraisal" />,
            score:<FormattedMessage id="ui-party.loans.columns.party.appraisal.score"/>,
            checker: <FormattedMessage id="ui-party.loans.columns.party.appraisal.checker" />,
            createDate:<FormattedMessage id="ui-party.loans.columns.party.appraisalDate" />,
          }}
          columnWidths={{
            serialNumber:'5%',
            checkBox: '5%',
            partyName: '10%',
            readName: '10%',
            appraisal: '30%',
            score:"5%",
            state: '10%',
            createDate: '15%',
            // operation: '15%'
          }}
        />
      </div>
    );
  }
}

 

export default stripesConnect(list);